import React, { useState, useEffect, useRef } from 'react'
import {
	Button,
	Modal,
	Switch,
	message
} from 'antd'
import {
	DeleteOutlined,
	EditOutlined,
	ExclamationCircleOutlined
} from '@ant-design/icons'
import UserForm from '../../../components/userManage/UserForm.js'
import './index.css'
import { getAllDepartment, getAllRole, getAllUser, getLoginUserById } from '../../../utils/request/get.js'
import { changeRoleState, updateLoginUserById, updateUserById } from '../../../utils/request/put.js'
import { deleteLoginUserByUserId, deleteUserById } from '../../../utils/request/delete.js'
import { addLoginUser, addUser } from '../../../utils/request/post.js'
import MyTable from '../../../components/newsSandBox/MyTable.js'
import axios from 'axios'

const { confirm } = Modal
const cancelTokenSource = axios.CancelToken.source()

export default function UserList() {
	const [dataSource, setDataSource] = useState([])
	const [isAddVisible, setIsAddVisible] = useState(false)
	const [isUpdateVisible, setIsUpdateVisible] = useState(false)
	const [isUpdateDisable, setIsUpdateDisable] = useState(false)
	const [departments, setDepartments] = useState([])
	const [roles, setRoles] = useState([])
	const [currentUser, setCurrentUser] = useState(null)
	const addForm = useRef(null)
	const updateForm = useRef(null)

	useEffect(() => {
		getAllUser().then(res => {
			const data = res.data.users
			let list = []
			data.forEach(item => {
				let obj = {}
				obj["id"] = item.id
				obj["department"] = item.Department.departmentName
				obj["roleId"] = item.roleId
				obj["roleName"] = item.Role.roleName
				obj["username"] = item.username
				obj["phoneNumber"] = item.phoneNumber
				obj["gender"] = item.gender
				obj["roleState"] = item.roleState
				list.push(obj)
			});
			// 多级权限
			// setDataSource(roleObj[roleId] === 'admin' ? list : [
			// 	...list.filter(item => item.username === username),
			// 	...list.filter(item => item.departmentName === departmentName && roleObj[item.roleId] === "server")
			// ])
			setDataSource(list)
		})
		axios.get('/user', { cancelToken: cancelTokenSource.token }).then(res => {
			console.log(res.data);
		}).catch(err => {
			if (axios.isCancel(err)) {
				// 可接收取消的原因 => err.message 
				console.log("is Cancel", err.message);
			} else {
				console.log(err);
			}
		})
		// 取消的原因
		cancelTokenSource.cancel("取消请求");
	}, [])

	useEffect(() => {
		getAllDepartment().then(res => {
			setDepartments(res.data.departments)
		})
	}, [])

	useEffect(() => {
		getAllRole().then(res => {
			setRoles(res.data.roles)
		})
	}, [])

	const changeState = (item) => {
		item.roleState = !item.roleState
		setDataSource([...dataSource])
		changeRoleState(item.id, item.roleState)
	}

	const deleteData = async (item) => {
		setDataSource(dataSource.filter(data => data.id !== item.id))
		const res = await deleteUserById(item.id)
		const loginUserRes = await deleteLoginUserByUserId(item.id)
		if (res && loginUserRes) {
			message.success(res.data.msg)
		} else {
			message.error(res.data.msg)
		}
	}

	const addDepartmentId = (value) => {
		for (let i = 0; i < departments.length; i++) {
			let item = departments[i]
			if (item.departmentName === value.department) {
				value['departmentId'] = item.id
				break
			}
		}
		return value
	}

	const getRoleName = (user, roleId) => {
		for (let i = 0; i < roles.length; i++) {
			const item = roles[i];
			if (item.id === roleId) {
				user['roleName'] = item.roleName
			}
		}
		return user
	}

	const getDepartmentName = (user, departmentId) => {
		for (let i = 0; i < departments.length; i++) {
			const item = departments[i];
			if (item.id === departmentId) {
				user['department'] = item.departmentName
			}
		}
		return user
	}

	const showError = (err) => {
		const errors = err.errorFields
		if (errors.length > 0) {
			message.warning(errors[0].errors[0])
		}
	}

	const addFormMethod = () => {
		addForm.current.validateFields().then(value => {
			setIsAddVisible(false)
			addForm.current.resetFields()
			let obj = { // 默认添加的属性
				roleState: true,
				default: false
			}
			value = addDepartmentId(value)
			const loginInfo = {
				username: value.username,
				password: value.password,
				roleId: value.roleId
			}
			addUser({ ...obj, ...value }).then(res => {
				// console.log(res.data.user);
				const data = res.data.user
				const { roleId, departmentId, id } = data
				addLoginUser({ userId: id, ...loginInfo })
				setTimeout(() => {
					let user = data
					user = getRoleName(user, roleId)
					user = getDepartmentName(user, departmentId)
					setDataSource([...dataSource, { ...user }])
				}, 0)
			})
		}).catch(err => { showError(err) })
	}

	const updateFormMethod = () => {
		updateForm.current.validateFields().then(async value => {
			setIsUpdateVisible(false)
			setIsUpdateDisable(!isUpdateDisable)
			setDataSource(dataSource.map(item => {
				if (item.id === currentUser.id) {
					// console.log(roles.filter(data => data.id === value.roleId)[0]);
					return {
						...item,
						...value
					}
				}
				return item
			}))
			value = addDepartmentId(value)
			for (let i = 0; i < dataSource.length; i++) {
				let item = dataSource[i]
				if (item.id === currentUser.id) {
					value['roleState'] = item.roleState
					break
				}
			}
			// console.log(value);
			value["userId"] = currentUser.id;
			updateUserById(currentUser.id, value)
			const loginRes = await getLoginUserById(currentUser.id)
			const data = loginRes.data.loginUser
			if (data.length === 0)
				return message.error('修改失败')
			const loginId = data.id
			updateLoginUserById(loginId, value)
		}).catch(err => { showError(err) })
	}

	const showUpdateForm = (item) => {
		// react中状态更新不一定是同步的，导致表单还没挂载就调用了setFieldsValue，所以报错
		setIsUpdateVisible(true)
		// 解决办法： 等待表单显示（即挂载完成）再向下执行
		setTimeout(() => { // 将 表单挂载 和 设置表单的值 这两步操作变成同步执行（即一步步执行）
			if (item.roleId === 1) {
				setIsUpdateDisable(true)
			} else {
				setIsUpdateDisable(false)
			}
			updateForm.current.setFieldsValue(item)
		}, 0)
		setCurrentUser(item)
	}

	const showConfirm = (type, item) => {
		let obj = {
			icon: <ExclamationCircleOutlined />,
		}
		switch (type) {
			case 'CANCEL':
				obj.title = '您确定要取消吗?'
				obj.onOk = function () { }
				obj.onCancel = function () { console.log('Cancel'); }
				break
			case 'DELETE':
				obj.title = '您确定要删除吗?'
				obj.cancelText = '取消'
				obj.okText = '确定'
				obj.onOk = function () { deleteData(item); }
				obj.onCancel = function () { console.log('Cancel'); }
				break
			default: break
		}
		confirm(obj)
	};

	const columns = [
		{
			title: '部门',
			dataIndex: 'department',
			filters: [...departments.map(item => ({
				text: item.departmentName,
				value: item.departmentName,
			}))],
			onFilter: (value, record) => {
				return record.department.indexOf(value) === 0

			},
			render: (department) => {
				return <b>{department}</b>
			}
		},
		{
			title: '角色名称',
			dataIndex: 'roleName'
		},
		{
			title: '用户名',
			dataIndex: 'username'
		},
		{
			title: '手机号',
			dataIndex: 'phoneNumber'
		},
		{
			title: '性别',
			dataIndex: 'gender'
		},
		{
			title: '用户状态',
			dataIndex: 'roleState',
			render: (roleState, item) => {
				return <Switch disabled={item.default} checked={roleState}
					onChange={() => changeState(item)} />
			}
		},
		{
			title: '操作',
			render: (record) => {
				return (
					<div>
						<Button
							disabled={record.default}
							danger onClick={() => showConfirm("DELETE", record)}
							shape="circle" icon={<DeleteOutlined />}>
						</Button>&nbsp;&nbsp;
						<Button
							disabled={record.default}
							shape="circle"
							icon={<EditOutlined />}
							type="primary"
							onClick={() => { showUpdateForm(record) }}></Button>
					</div>
				)
			}
		}
	]

	return (
		<>
			<Button
				type="primary"
				style={{ marginBottom: '5px' }} onClick={() => setIsAddVisible(true)}>添加用户</Button>
			<MyTable
				bordered
				columns={columns}
				dataSource={dataSource}
				pageSize={5}
				rowKey={(item) => item.id}
				params={{
					size: 'middle',
					bordered: true,
					rowClassName: { textAlign: 'center' },
					scroll: {
						y: 420,
					}
				}}
			/>
			{/* <Table
				bordered
				columns={columns}
				dataSource={dataSource}
				pagination={{ pageSize: 5 }}
				rowKey={(item) => item.id}
			/> */}
			<Modal
				className='modal'
				open={isAddVisible}
				title="添加用户"
				okText="完成"
				cancelText="取消"
				onCancel={() => setIsAddVisible(false)}
				onOk={() => addFormMethod()}
			>
				<UserForm ref={addForm} departments={departments} roles={roles}></UserForm>
			</Modal>
			<Modal
				className='modal'
				open={isUpdateVisible}
				title="更新用户"
				okText="更新"
				cancelText="取消"
				onCancel={() => {
					setIsUpdateVisible(false)
					setIsUpdateDisable(!isUpdateDisable)
				}
				}
				onOk={() => updateFormMethod()}
			>
				<UserForm ref={updateForm} departments={departments} roles={roles}
					isUpdateDisable={isUpdateDisable} isUpdate={true}></UserForm>
			</Modal>
		</>
	)
}